define(["jquery","echarts",'migrate_jqprint','jqprint',"bbcare",
    "as/app/mabc/mabcDetailInfo.ui",
    "as/app/mabc/mabcDetailInfo.servers","as/app/mabc/report"],function(jquery,echarts,migrate,$print,$bb,$ui,$servers,$report,$html2canvas){
    var event = {};
    event.init = function(info){
 		$(".panel-title.goBack").bind("click",function(){
 			$bb.openPage("mabcDetail",{params:info});
		})
    };
    //基础问卷的回调函数：
    event.mabcBaseInfo = function(data,params){
		var classAge = ''
        for (var i = 0; i < params.length; i++) {
            if (params[i].name.indexOf('孩子所在年级') > -1) {
                console.log(params[i].answer)
                for (var j = 0; j < params[i].answer.length; j++) {
                    if (params[i].answer[j].checked) {
                        classAge = params[i].answer[j].name.split('.')[1]
                    }
                }
            }
        }
        data.data.class = classAge
        console.log(data.data)
    	$ui.infoInit({"id":"#mabcDetailInfo","data":data.data});
    };
    //问卷列表的回调函数：
    event.getMabcQuestionList = function(data,params){
		/**
		 *  单独处理 7 岁问卷的 Id 顺序触发的问题
		 * 	完全是为了修补完成任务 没有逻辑
		 */
		var hasChildren = {
			'2': ['21', '22', '23', '24', '25', '26', '27', '28', '29', '210', '2101', '2102', '2103','211', '2111', '2112','212', '2121', '2122', '213', '2131', '214', '215','216'],
			'24': ['25'],
			'210': ['2101', '2102', '2103'],
			'211': ['2111', '2112'],
			'212': ['2121', '2122'],
			'213': ['2131'],
			'4': ['41', '42', '43'],
			'5': ['51', '52', '53'],
			'6': ['61', '62', '63'],
			'8': ['81', '82', '83'],
			'9': ['91', '92', '93']
		}
		if (data.data.answerResult) {
			var list = data.data.answerResult[0].questions
			var results = []
			list.forEach(function (l) {
				if (!l.answer) return
				l.answer.forEach(function (a) {
					if (a.checked && a.id == '1' && hasChildren[l.id]) {
						results = results.concat(hasChildren[l.id])
					}
				})
			})
			list.forEach(function (q) {
				if (results.indexOf(q.id) > -1) {
					if (q.value) delete q.value
					if (q.answer) {
						q.answer.forEach(function (a) {
							if (a.checked) delete a.checked
						})
					}
				}
			})
		}

		setTimeout(function () {
			$ui.questListInit({"id":"#mabcQuestList","data":data.data});
			params.modelId = 0;
			event.answerList(data,params)
			$(".mabcModel").on("click",function(){
				params.model = $(this).parent();
				params.modelId = $(this).attr("answerId");
				if(params.modelId == -1){
					$(".mabcModel").parent().removeClass("active");
					$(params.model).addClass("active");
					$("#mabcwindowTit").removeClass("col-sm-11 col-md-11").addClass("col-sm-9 col-md-9").text("/"+params.busiName+"/评估报告");
					$("#print").parent().addClass("col-sm-2 col-md-2");
					$("#print").text("打印报告");
					data.data.guide = data.data.guide?data.data.guide:{guideId:$(".docGuid").attr("guideId"),guideContent:$(".docGuid").val()};
					var inParams = {
						userId:params.userId,
						answerId:params.answerId,
						guideId:data.data.guide.guideId,
						guide:data.data.guide.guideContent,
					};
					$servers.getGuides(inParams,function(guide,param){
						guide.data =  guide.data || {};
						data.data.guideContent = guide.data.guide;
						data.data.guideId = data.data.guide.guideId;
						data.data.userName = params.userName;
						data.data.gender = params.gender == "F"?"女":"男";
						data.data.age = params.age;
						$ui.report({"id":"#answerList","data":data.data});
						initChartData(eval("("+data.data.score+")"),params);
						$("#saveGuide").bind("click",function(){
							var guide = $(".docGuid").val();
							var inParams = {
								userId:params.userId,
								answerId:params.answerId,
								guideId:$(".docGuid").attr("guideId"),
								guide:guide
							}
							$servers.guidemodify(inParams,function(data,param){
								if(data.success){
									$("#guideDiv").text(guide);
									$bb.toastShow("保存成功",1500);
								}else{
									$bb.toastShow(data.msg,1500);
								}
							},params);
						})
						$("#print").bind("click",function(){
							event.printReport();
						})
					},params);
				}else{
					$("#mabcwindowTit").removeClass("col-sm-9 col-md-9").addClass(" col-sm-11 col-md-11");
					$("#print").parent().removeClass("col-sm-2 col-md-2");
					$("#print").text("")
					event.answerList(data,params);
				}
			})

		}, 500)
		
    };
    //问卷题目列表的回调函数：
    event.answerList = function(data,params){
    	if(params.model){
    		$(".mabcModel").parent().removeClass("active");
    		$(params.model).addClass("active");
    	}
    	if(data.data.answerResult.length==1){
    		$("#mabcwindowTit").text("/"+params.busiName)
    	}else{
    		$("#mabcwindowTit").text("/"+params.busiName+"/"+data.data.answerResult[params.modelId].name)
    	}
    	$.each(data.data.answerResult[params.modelId].questions,function(a,b){
    		var ischecked = true;
    		$.each(b.answer,function(c,d){
    			if(d.checked){
    				ischecked = false;
    			}
    		})
    		if(ischecked){
    			b.ischecked = ischecked;
    		}
    	})
		$ui.answerList({"id":"#answerList","data":data.data.answerResult[params.modelId].questions});
    };
    var initChartData = function(data,params){
    	var colors = {"正常":"#30d9ba","低风险":"#ffb257","异常":"#ff0000","发育良好":"#30d9ba","风险偏高":"#ff0000"}
		var labels = function(isSdq){
			var labels = [];
			if(isSdq){
				labels.push({
					name:"发育良好",
                	color:colors["发育良好"]
				})
				labels.push({
					name:"低风险",
                	color:colors["低风险"]
				})
				labels.push({
					name:"风险偏高",
                	color:colors["风险偏高"]
				})
			}else{
				labels.push({
					name:"正常",
                	color:colors["正常"]
				})
				labels.push({
					name:"风险偏高",
                	color:colors["异常"]
				})
			}
			return labels;
		}(data.score.diffTotal?1:0)
		data.score.total =  data.score.total ||{};
		data.score.total.score =  data.score.total.score ||　data.score.diffTotal.score;
		data.score.total.result =  data.score.total.result || data.score.diffTotal.result;
		$("#maxScore").text(data.score.total.score+"分");
		$(".mainTitle").text("您的"+params.busiName+"报告");
		$("#testTime").text(data.testTime);
		if(data.score.total.result == "正常"||data.score.total.result == "发育良好"){
		     $("#maxScore").css("color",colors["正常"]);
		     if(!data.score.diffTotal){
		    	$("#diffTotalTip").empty().append("您的宝宝睡眠质量良好","<p>请咨询医生</p>").addClass("color4");
		    }else{
		     	$("#diffTotalTip").empty().append("您的"+params.busiName+"正常").css("color",colors["正常"]);
		    }
		}else if(data.score.total.result == "低风险"){
		    $("#maxScore").removeClass("color2").css("color",colors["低风险"]);
		    $("#diffTotalTip").empty().append("您的"+params.busiName+"存在低风险","<p>请咨询医生</p>").css("color",colors["低风险"]);
		}else{
		    $("#maxScore").css("color",colors["风险偏高"]);
		    if(!data.score.diffTotal){
		    	$("#diffTotalTip").empty().append("您的宝宝睡眠质量不良","<p>请咨询医生</p>").addClass("color4");
		    }else{
		     	$("#diffTotalTip").empty().append("您的"+params.busiName+"风险偏高","<p>请咨询医生</p>").css("color",colors["风险偏高"]);
		    }
		}
		if(data.score.diffTotal){
			delete data.score.diffTotal;
			delete data.score.total;
		}
		initChart(data.score,data.maxScore,colors,labels);
		if(data.score.emotional){
			$(".bb-y-val-name").css("right","-3.4rem");
		}
    }
    var initChart = function(data,maxscore,colors,labels,params){
    	var names = [],values =[];
		$.each(data,function(a,b){
			if(a != "total"){
				names.push(b.desc)
				values.push({
                    name:b.result,
                    score:b.score,
                    color:colors[b.result],
                })
			}
		})
        $report.init({
        	id:"bb-report",
           labels:labels,
            x : {
                title : "评估维度",
                names : names,
                values: values
            },
            y : {
                title : "评估分数",
                min : 0,
                max : maxscore
            } 
        })
    };
    //打印函数：
    event.printReport = function(){
    	$(".reportBaseInfo.uhide").removeClass("uhide");
    	$("#guideDiv.uhide").removeClass("uhide");
    	$("#guide,#saveGuide").addClass("uhide");
    	var timer = setTimeout(function(){
    		$(".reportBaseInfo").addClass("uhide");
    		$("#guideDiv").addClass("uhide");
    		$("#guide.uhide,#saveGuide.uhide").removeClass("uhide");
    		clearTimeout(timer);
    	},1)
        $("#answerList").jqprint({
            debug: false, //如果是true则可以显示iframe查看效果（iframe默认高和宽都很小，可以再源码中调大），默认是false
            importCSS: true, //true表示引进原来的页面的css，默认是true。（如果是true，先会找$("link[media=print]")，若没有会去找$("link")中的css文件）
            printContainer: true, //表示如果原来选择的对象必须被纳入打印（注意：设置为false可能会打破你的CSS规则）。
            operaSupport: true//表示如果插件也必须支持歌opera浏览器，在这种情况下，它提供了建立一个临时的打印选项卡。默认是true
        });
        return;
    };
    return event;
});